package com.ow.dva.util;

import cn.hutool.json.JSONUtil;
import org.slf4j.Logger;

import javax.servlet.http.HttpServletRequest;
import java.util.stream.IntStream;

/**
 * 描述 :
 * 包名 : com.ow.dva.util
 * 作者 : GaoXiang
 * 时间 : 19-12-17
 * 版本 : V1.0
 */
public class RequestUtil {

    public static void printRequestErrorInfo(Logger logger,HttpServletRequest request, Exception e){
        logger.error("================== 「拦截到异常信息」「BEGIN」 ==================");
        printRequest(logger, request);
        logger.error("异常详情：" + e.toString());
        logger.error("异常信息：" + e.getMessage());
        // 默认错误异常打印
        e.printStackTrace();
        // 自定义异常打印
//        StackTraceElement[] stackArray = e.getStackTrace();
//        logger.error("异常描述：" + stackArray[0].toString());
//        IntStream.range(0, stackArray.length).forEach(i -> {
//            StackTraceElement element = stackArray[i];
//            logger.error("异常详情[" + i + "]：" + element.toString());
//        });
        logger.error("================== 「拦截到异常信息」「E N D」 ==================");
    }

    public static void printRequest(Logger logger, HttpServletRequest request) {
        logger.error("资源路径：" + request.getServletPath());
        logger.error("请求参数：" + request.getQueryString());
        logger.error("请求表单：" + JSONUtil.toJsonStr(request.getParameterMap()));
        logger.error("请求协议：" + request.getScheme()  + " - " + request.getProtocol());
        logger.error("请求方式：" + request.getMethod());
        logger.error("请求编码：" + request.getCharacterEncoding());
        logger.error("请求格式：" + request.getContentType());
        logger.error("请求大小：" + request.getContentLength());
        logger.error("请求地址：" + request.getRemoteAddr());
        logger.error("目标主机：" + request.getServerName());
        logger.error("目标端口：" + request.getServerPort());
    }

}
